
#import "MdIAPManager.h"

@interface MdIAPManager ()

@end

@implementation MdIAPManager

+ (instancetype)sharedmdManage {
    static MdIAPManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}

- (void)pchasemdbyProductID:(NSString *)productID
                  completion:(MdIAPcompHandler)completion {
    
    if (![SKPaymentQueue canMakePayments]) {
        NSError *error = [NSError errorWithDomain:@"IAPErrorDomain"
                                             code:0
                                         userInfo:@{NSLocalizedDescriptionKey: @"Users are prohibited from making in app purchases"}];
        completion(NO, error);
        return;
    }
    
    self.mdcompHandler = completion;
    self.currtProID = productID;
    
    NSSet *productIdentifiers = [NSSet setWithObject:productID];
    SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
    productsRequest.delegate = self;
    [productsRequest start];
}

#pragma mark - SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    SKProduct *product = [response.products firstObject];
    if (product) {
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    } else {
        NSError *error = [NSError errorWithDomain:@"IAPErrorDomain"
                                             code:1
                                         userInfo:@{NSLocalizedDescriptionKey: @"Product not found"}];
        self.mdcompHandler(NO, error);
        self.mdcompHandler = nil;
    }
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    self.mdcompHandler(NO, error);
    self.mdcompHandler = nil;
}

#pragma mark - SKPaymentTransactionObserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchased:
                [self completemonoTtion:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self restoreTaction:transaction];
                break;
            default:
                break;
        }
    }
}

- (void)completemonoTtion:(SKPaymentTransaction *)transaction {
    if ([transaction.payment.productIdentifier isEqualToString:self.currtProID]) {
        self.mdcompHandler(YES, nil);
        self.mdcompHandler = nil;
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)restoreTaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)failedTction:(SKPaymentTransaction *)transaction {
    if ([transaction.payment.productIdentifier isEqualToString:self.currtProID]) {
        self.mdcompHandler(NO, transaction.error);
        self.mdcompHandler = nil;
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end
